<template>
  <div class="login">
    <input type="text" placeholder="请输入用户名" v-model="username" />
  </div>
  <div class="home">
    <input type="text" placeholder="请输入消息" v-model="msg" />
    <button @click="handleSendBtnClick">发送</button>
  </div>
  <div>
    <div class="tg-taolunqu-cont-title">
      <div class="tg-taolunqu-title-left fl">
        <span class="tg-taolunqu-title-left-icon"></span>
        讨论区
      </div>
    </div>
    <div
      class="tg-taolunqu-xioaxi-box"
      style="height: 380px; min-height: 380px"
    >
      <li v-for="item of msgList" :key="item.id">
        <p>
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.dateTime) }}</span>
        </p>
        <p>消息:{{ item.msg }}</p>
      </li>
    </div>
  </div>
</template>

<script>
const ws = new WebSocket("ws://localhost:8000");

export default {
  name: "Home",
  data() {
    return {
      msg: "",
      username: "",
      msgList: [],
    };
  },
  mounted() {
    // 初始化
    ws.addEventListener("open", this.handleWsOpen.bind(this), false);
    ws.addEventListener("close", this.handleWsClose.bind(this), false);
    ws.addEventListener("error", this.handleWsError.bind(this), false);
    ws.addEventListener("message", this.handleWsMessage.bind(this), false);
  },
  methods: {
    handleSendBtnClick() {
      if (this.username) {
        const msg = this.msg;
        if (!msg.trim().length) {
          return;
        }
        ws.send(
          JSON.stringify({
            id: new Date().getTime(),
            user: this.username,
            dataTime: new Date().getTime(),
            msg: this.msg,
          })
        );
        this.msg = "";
      }
    },
    handleWsOpen(e) {
      console.log("handleWsOpen", e);
    },
    handleWsClose(e) {
      console.log("handleWsClose", e);
    },
    handleWsError(e) {
      console.log("handleWsError", e);
    },
    handleWsMessage(e) {
      //接受信息
      console.log("handleWsMessage", e);
      const msg = JSON.parse(e.data);
      this.msgList.push(msg);
    },
  },
};
</script>

<style scoped>
.tg-taolunqu-cont-title {
  height: 52px;
  line-height: 48px;
  padding: 0 16px;
  border-bottom: 1px solid #e5e5e5;
}

.tg-taolunqu-title-left {
  padding-left: 20px;
  position: absolute;
  font-size: 18px;
  color: #333;
}

.tg-taolunqu-title-left-icon {
  content: "";
  position: absolute;
  left: 0;
  top: 15px;
  height: 20px;
  width: 6px;
  background: #ca2630;
  border-radius: 2px;
}

.tg-taolunqu-xioaxi-box {
  overflow: auto;
  border: 1px solid #e5e5e5;
  border-top: none;
}

.tg-zhiboqu-xiaoxi:hover {
  background-color: #f0f8ff;
}

.tg-zhiboqu-xiaoxi:hover .tg-zhiboqu-xiaoxi-btn-box {
  display: block;
  position: absolute;
  right: 20px;
  top: 16px;
}
</style>
